package cn.liit.weixin.core.basic.jsapi;

import java.util.Calendar;
import java.util.Map;

import cn.liit.weixin.core.basic.accesstoken.AccessTokenSupport;
import cn.liit.weixin.core.config.Config;
import name.zbq.bush.utils.DateUtil;
import name.zbq.bush.utils.http.HttpConnect;


/**
 * AccessToken提供类
 * @author boqi.zhang
 */
public class JsapiTicketSupport {
	public static final String APIURL = "https://api.weixin.qq.com/cgi-bin/ticket/getticket";
	/**
	 * 从微信服务器加载access_token 且此方法不对当前包外开放
	 * @param apiurl 微信获取access_token接口地址
	 * @param appid appid
	 * @param secret appsecret
	 * @return
	 */
	public static JsapiTicket loadJsapiTicket(String apiurl,String accessToken){
		apiurl = String.format("%s?access_token=%s&type=jsapi", apiurl.trim(),accessToken.trim());
		JsapiTicket jsapiTicket = null;
		Map<String,Object> data = HttpConnect.getInstance().doGetJson(apiurl, null,"UTF-8");
		if("0".equals(data.get("errcode").toString())){
			jsapiTicket = JsapiTicket.getInstance();
			jsapiTicket.setJsapi_ticket(data.get("ticket").toString());
			jsapiTicket.setExpires_in(Integer.parseInt(data.get("expires_in").toString()));
			jsapiTicket.setExpires_date(DateUtil.getLater(DateUtil.getCurrentDate(), Calendar.SECOND, jsapiTicket.getExpires_in()));
			jsapiTicket.setIsloaded(true);//标记已经加载过
		}
		return jsapiTicket;
	}
	/**
	 * 获取JsapiTicket对象
	 * @return
	 */
	public synchronized static JsapiTicket getJsapiTicket(){
		JsapiTicket jsapiTicket = JsapiTicket.getInstance();
		//提前十分钟
		if(!jsapiTicket.isIsloaded() || jsapiTicket.getExpires_date().before(DateUtil.getLater(DateUtil.getCurrentDate(), Calendar.SECOND, 600))){
			loadJsapiTicket(APIURL, AccessTokenSupport.getAccess_token());
		}
		return jsapiTicket;
	}
	/**
	 * 获取access_token
	 * @return
	 */
	public static String getJsapi_ticket(){
		JsapiTicket accessToken = getJsapiTicket();
		return accessToken.getJsapi_ticket();
	}
	/**
	 * 获取expire_in
	 * @return
	 */
	public static Integer getExpire_in(){
		JsapiTicket accessToken = getJsapiTicket();
		return accessToken.getExpires_in();
	}
	
	private JsapiTicketSupport(){
	}
}
